/**
 * @file    list.c
 * @author  zhouh
 * @date    2025-06-03
 * @version V0.1
 */
#include <stdio.h>
#include "list.h"

/**
 * @brief   初始化列表节点
 * @param   item 列表节点指针
 */
void list_item_init(list_item_t *const item)
{
    item->container = NULL; // 所属链表为空，未插入任何链表
}

/**
 * @brief   链表根节点初始化
 * @param   list --> 根节点指针
 */
void list_init(list_t *const list)
{
    list->index = (list_item_t *) (&list->mini_item); // 列表指向末尾节点
    list->mini_item->item_value = MAX_LIST_ITEM_NUM;
    list->mini_item->next = (list_item_t *) (&list->mini_item);
    list->mini_item->prev = (list_item_t *) (&list->mini_item);
    list->item_num = 0u;
}

/**
 * @brief   将节点插入队尾之前
 * @param   list --> 被插入链表
 * @param   new_item --> 需要插入的节点
 */
void list_insert_end(list_t *const list, list_item_t *const new_item)
{
    list_item_t *const index = list->index; // 提取根节点索引指针

    new_item->next = index;
    new_item->prev = index->prev;
    new_item->container = (void *) list;

    index->prev->next = new_item->prev;
    index->prev = new_item;

    list->item_num++;
}

/**
 * @brief   按照升序将节点插入链表中
 * @param   list --> 被插入的链表
 * @param   new_item --> 插入的节点
 */
void list_insert(list_t *const list, list_item_t *const new_item)
{
    list_item_t *iterator;
    tick_t new_item_value = new_item->item_value; // 取出插入节点排序值

    if (new_item_value == MAX_LIST_ITEM_NUM)
    {
        iterator = list->mini_item->prev;
    }
    else
    {
        for (iterator = (list_item_t *) &(list->mini_item);
             iterator->next->item_value <= new_item_value;
             iterator = iterator->next);
    }

    new_item->next = iterator->next;
    new_item->next->prev = new_item;
    new_item->prev = iterator;
    iterator->next = new_item;
}
